<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\CampusList;
use app\common\model\CoachList;
use app\common\model\CourseList;
use app\common\model\ExperienceCourseList;
use app\common\model\GroupWork;
use app\common\model\StudentsList;
use app\common\model\Area;
use app\common\model\User;
use app\common\model\TuanCourseList;
use app\common\model\Order;
use think\Db;
/**
 * 课程接口
 */
class Course extends Api
{
    /**
     * 课程列表
     * @param string $token TOKEN
     * @param int $type 1拼团课程2普通课程3体验课程
     * @param int $page 页数，默认为1
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1610693977",
    "data": [{
    "id": 1,课程ID
    "name": "2人拼团大礼包",
    "images": "http:\/\/www.kecheng.com\/uploads\/20210114\/194ecb5cc329eb0a2433f181d70d5340.png",课程图片
    "class": 4,课时
    "original_price": "355.00",原价
    "price": "200.00",现价
    "spell_group": 2,拼团人数（拼团课程才需要）
    "content": "这是拼团课程…",简介
    "status_text": ""
    }]
    })
     */
    public function course_list()
    {
        $token = $this->request->get('token') ;
        $type = $this->request->get('type') ;
        $pagesize = 10;
        $page  = $this->request->get('page')==null?1:$this->request->get('page');
        $page = ($page-1)*$pagesize;
        if($type == 1){
            $list = TuanCourseList::where('status',0)->field('id,name,images,class,original_price,price,spell_group,content')->limit($page,$pagesize)->order('spell_group asc')->order('class asc')->select();
        }elseif($type ==2){
            $list = CourseList::where('status',0)->field('id,name,images,class,original_price,price,content')->limit($page,$pagesize)->order('price asc')->order('class asc')->select();
        }elseif($type == 3){
            $list = ExperienceCourseList::where('status',0)->field('id,name,images,class,original_price,price,spell_group,content')->limit($page,$pagesize)->order('price asc')->order('class asc')->select();
        }else{
            $this->error('数据不存在');
        }
        foreach($list as &$value){
            $images = explode(',',$value['images']);
            $value['images'] =$this->domain.$images[0];
            $value['content'] = StringToText($value['content'],20);
        }
        $this->success($list);
    }
    /**
     * 普通课程详情
     * @param string $token TOKEN
     * @param int $id 普通课程ID
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1610703133",
    "data": {
    "id": 1,课程ID
    "name": "篮球新人礼包",课程名称
    "images": ["http:\/\/www.kecheng.com\/uploads\/20210114\/1eb5f2ea54992ecd8af7d543c733afcd.png", "http:\/\/www.kecheng.com\/uploads\/20210114\/194ecb5cc329eb0a2433f181d70d5340.png"],课程图片
    "class": 1,课时
    "original_price": "500.00",原价
    "price": "300.00",现价
    "content": "<p>简介简介简介简介简介简介<img src=\"http:\/\/www.kecheng.com\/uploads\/20210115\/000218d1f0a68413bdc7c22c28809fe9.jpg\" ><\/p>",课程介绍
    "status_text": ""
    }
    })
     */
    public function course_detail()
    {
        $token = $this->request->get('token') ;
        $id = $this->request->get('id') ;
        $user_info = User::where('token',$token)->field('id')->find();
        $info = CourseList::where('id',$id)->where('status',0)->field('id,name,images,class,original_price,price,content,coach_name')->find();
        if($info){
            $images = explode(',',$info['images']);
            foreach($images as &$v){
                $v = $this->domain.$v;
            }
            $info['images'] = $images;
            $info['content'] = get_img_thumb_url($info['content'],$this->domain);
            $info['userid']=  $user_info['id'];
            $this->success($info);
        }
        $this->error('课程不存在');
    }
    /**
     * 体验课程详情
     * @param string $token TOKEN
     * @param int $id 普通课程ID
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1610703133",
    "data": {
    "id": 1,课程ID
    "name": "篮球新人礼包",课程名称
    "images": ["http:\/\/www.kecheng.com\/uploads\/20210114\/1eb5f2ea54992ecd8af7d543c733afcd.png", "http:\/\/www.kecheng.com\/uploads\/20210114\/194ecb5cc329eb0a2433f181d70d5340.png"],课程图片
    "class": 1,课时
    "original_price": "500.00",原价
    "price": "300.00",现价
    "content": "<p>简介简介简介简介简介简介<img src=\"http:\/\/www.kecheng.com\/uploads\/20210115\/000218d1f0a68413bdc7c22c28809fe9.jpg\" ><\/p>",课程介绍
    "status_text": ""
    }
    })
     */
    public function experience_course_detail()
    {
        $token = $this->request->get('token') ;
        $user_info = User::where('token',$token)->field('id')->find();
        $id = $this->request->get('id') ;
        $info = ExperienceCourseList::where('id',$id)->where('status',0)->field('id,name,images,class,original_price,price,content,coach_name')->find();
        if($info){
            $images = explode(',',$info['images']);
            foreach($images as &$v){
                $v = $this->domain.$v;
            }
            $info['images'] = $images;
            $info['content'] = get_img_thumb_url($info['content'],$this->domain);
            $info['userid']=  $user_info['id'];
            $this->success($info);
        }
        $this->error('课程不存在');
    }
    /**
     * 拼团课程详情
     * @param string $token TOKEN
     * @param int $id 普通课程ID
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1610703133",
    "data": {
    "id": 1,课程ID
    "name": "篮球新人礼包",课程名称
    "images": ["http:\/\/www.kecheng.com\/uploads\/20210114\/1eb5f2ea54992ecd8af7d543c733afcd.png", "http:\/\/www.kecheng.com\/uploads\/20210114\/194ecb5cc329eb0a2433f181d70d5340.png"],课程图片
    "class": 1,课时
    "original_price": "500.00",原价
    "price": "300.00",现价
    "content": "<p>简介简介简介简介简介简介<img src=\"http:\/\/www.kecheng.com\/uploads\/20210115\/000218d1f0a68413bdc7c22c28809fe9.jpg\" ><\/p>",课程介绍
    "spell_group": 2,拼团人数
    "group_list": [拼团列表
    {
    "id": 3,拼图ID
    "kecheng_id": 1,课程ID
    "userid": 1,发起人userid
    "num": 2,剩余拼团人数
    "status": 0,
    "createtime": 1610960082,
    "username": "admin",用户昵称
    "avatar": "/uploads/20210114/5be5ea2c9ab7dedd4cdce5d09ad82c5b.png",头像
    "status_text": "Status 0"
    }
    ],
    "status_text": ""
    }
    })
     */
    public function tuan_course_detail()
    {
        $token = $this->request->get('token') ;
        $id = $this->request->get('id') ;
        $user_info = User::where('token',$token)->field('id')->find();
        $info = TuanCourseList::where('id',$id)->where('status',0)->field('id,name,images,class,original_price,price,content,spell_group,coach_name')->find();
        if($info){
            $images = explode(',',$info['images']);
            foreach($images as &$v){
                $v = $this->domain.$v;
            }
            $info['images'] = $images;
            $info['content'] = get_img_thumb_url($info['content'],$this->domain);
            //拼团列表
            $group_list = GroupWork::where('kecheng_id',$info['id'])->where('status',1)->limit(2)->order('id desc')->select();
            $group_count = GroupWork::where('kecheng_id',$info['id'])->where('status',1)->count();
            foreach($group_list as &$value){
                $user_infos = User::where('id',$value['userid'])->field('username,avatar')->find();
                $value['username']=$user_infos['username'];
                $value['avatar']=$user_infos['avatar'];
                $value['num'] = $value['total_num'] - $value['num'];
            }
            $info['group_list'] = $group_list;
            $info['group_count'] = $group_count;
            $info['userid']=  $user_info['id'];
            $this->success($info);
        }
        $this->error('课程不存在');
    }
    /**
     * 拼团列表查看更多
     * @param string $token TOKEN
     * @param int $id 普通课程ID
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1610960445",
    "data": [
    {
    "id": 3,拼图ID
    "kecheng_id": 1,课程ID
    "userid": 1,发起人userid
    "num": 2,剩余拼团人数
    "status": 0,
    "createtime": 1610960082,
    "username": "admin",用户昵称
    "avatar": "/uploads/20210114/5be5ea2c9ab7dedd4cdce5d09ad82c5b.png",头像
    "status_text": "Status 0"
    }
    ]
    })
     */
    public function tuan_course_detail_more()
    {
        $token = $this->request->get('token') ;
        $id = $this->request->get('id') ;
        $group_list = GroupWork::where('kecheng_id',$id)->where('status',1)->order('id desc')->select();
        foreach($group_list as &$value){
            $user_info = User::where('id',$value['userid'])->field('username,avatar')->find();
            $value['username']=$user_info['username'];
            $value['avatar']=$user_info['avatar'];
        }
        $this->success($group_list);
    }
    /**
     *  体验课程立即支付
     * @ApiMethod   (POST)
     * @param int $id 课程ID
     * @param string $token TOKEN
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1597818634",
    "data": {
    "appId": "wx391cfb640d2fe50a",
    "nonceStr": "lb1sxq3i0i50mgskc1kapvfi5z88y5fj",
    "package": "prepay_id=wx191430346997680c3a836fe6d5c1fd0000",
    "signType": "MD5",
    "timeStamp": "1597818634",
    "paySign": "DA7DC8A98C5C21687323863BD03D58C9"
    }
    })
     */
    public function experience_course_pay_now()
    {
        $token = $this->request->post('token');
        $id = $this->request->post('id');
        $user_info = User::where('token',$token)->field('id,openid')->find();
        $info =  ExperienceCourseList::where('id',$id)->where(['status'=>0])->field('id,price')->find();
        if($info){
            $data = [
                'order_sn'=>getOrderSn(),
                'kecheng_id'=>$info['id'],
                'price'=>$info['price'],
                'userid'=>$user_info['id'],
                'type'=>2,
            ];
            Db::startTrans();
            try {
                $res = Order::create($data);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->apiError($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->apiError($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->apiError($e->getMessage());
            }
            if($res){
                $out_trade_no = $data['order_sn'];
                $amount =$info['price'];
                $jsapi = new Response();
                $result = $jsapi->wx_pay($out_trade_no, $amount, $user_info['openid']);
                $result = json_decode($result,true);
                return $this->success($result,'请求成功');
            }else{
                $this->error('请刷新重试');
            }
        }else{
            return $this->error('数据为空');
        }
    }
    /**
     *  普通课程立即支付
     * @ApiMethod   (POST)
     * @param int $id 课程ID
     * @param string $token TOKEN
     * @param string $share_id 分享人ID
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1597818634",
    "data": {
    "appId": "wx391cfb640d2fe50a",
    "nonceStr": "lb1sxq3i0i50mgskc1kapvfi5z88y5fj",
    "package": "prepay_id=wx191430346997680c3a836fe6d5c1fd0000",
    "signType": "MD5",
    "timeStamp": "1597818634",
    "paySign": "DA7DC8A98C5C21687323863BD03D58C9"
    }
    })
     */
    public function course_pay_now()
    {
        $token = $this->request->post('token');
        $id = $this->request->post('id');
        $share_id = $this->request->post('share_id')==null?0:$this->request->post('share_id');
        $user_info = User::where('token',$token)->field('id,openid')->find();
        $info =  CourseList::where('id',$id)->where(['status'=>0])->field('id,price')->find();
        if($info){
            $data = [
                'order_sn'=>getOrderSn(),
                'kecheng_id'=>$info['id'],
                'price'=>$info['price'],
                'userid'=>$user_info['id'],
                'share_id'=>$share_id,
                'type'=>0,
            ];
            Db::startTrans();
            try {
                $res = Order::create($data);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->apiError($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->apiError($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->apiError($e->getMessage());
            }
            if($res){
                $out_trade_no = $data['order_sn'];
                $amount =$info['price'];
                $jsapi = new Response();
                $result = $jsapi->wx_pay($out_trade_no, $amount, $user_info['openid']);
                $result = json_decode($result,true);
                return $this->success($result,'请求成功');
            }else{
                $this->error('请刷新重试');
            }
        }else{
            return $this->error('数据为空');
        }
    }
    /**
     *  拼团课程发起拼团
     * @ApiMethod   (POST)
     * @param int $id 课程ID
     * @param string $token TOKEN
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1597818634",
    "data": {
    "appId": "wx391cfb640d2fe50a",
    "nonceStr": "lb1sxq3i0i50mgskc1kapvfi5z88y5fj",
    "package": "prepay_id=wx191430346997680c3a836fe6d5c1fd0000",
    "signType": "MD5",
    "timeStamp": "1597818634",
    "paySign": "DA7DC8A98C5C21687323863BD03D58C9"
    }
    })
     */
    public function tuan_course_start_fight()
    {
        $token = $this->request->post('token');
        $id = $this->request->post('id');
        $user_info = User::where('token',$token)->field('id,openid')->find();
        $info =  TuanCourseList::where('id',$id)->where(['status'=>0])->field('id,price,spell_group')->find();
        if($info){
            $data = [
                'order_sn'=>getOrderSn(),
                'kecheng_id'=>$info['id'],
                'price'=>$info['price'],
                'userid'=>$user_info['id'],
                'type'=>1,
            ];
            $data1 = [
                'kecheng_id'=>$info['id'],
                'userid'=>$user_info['id'],
                'total_num'=>$info['spell_group'],
                'createtime'=>time(),
            ];
            Db::startTrans();
            try {
                $res = GroupWork::insertGetId($data1);
                if($res){
                    $data['group_work_id'] = $res;
                    $res1 = Order::create($data);
                }
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->apiError($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->apiError($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->apiError($e->getMessage());
            }
            if($res && $res1){
                $out_trade_no = $data['order_sn'];
                $amount =$info['price'];
                $jsapi = new Response();
                $result = $jsapi->wx_pay($out_trade_no, $amount, $user_info['openid']);
                $result = json_decode($result,true);
                return $this->success($result,'请求成功');
            }else{
                $this->error('请刷新重试');
            }
        }else{
            return $this->error('数据为空');
        }
    }
    /**
     *  拼团课程参与拼团
     * @ApiMethod   (POST)
     * @param int $id 课程ID
     * @param string $token TOKEN
     * @param string $group_work_id 拼团ID
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1597818634",
    "data": {
    "appId": "wx391cfb640d2fe50a",
    "nonceStr": "lb1sxq3i0i50mgskc1kapvfi5z88y5fj",
    "package": "prepay_id=wx191430346997680c3a836fe6d5c1fd0000",
    "signType": "MD5",
    "timeStamp": "1597818634",
    "paySign": "DA7DC8A98C5C21687323863BD03D58C9"
    }
    })
     */
    public function tuan_course_participate()
    {
        $token = $this->request->post('token');
        $id = $this->request->post('id');
        $group_work_id = $this->request->post('group_work_id');
        $user_info = User::where('token',$token)->field('id,openid')->find();
        $info =  TuanCourseList::where('id',$id)->where(['status'=>0])->field('id,price,spell_group')->find();
        if($info){
            //查看拼团信息是否存在
            $group_work_info = GroupWork::where('id',$group_work_id)->find();
            if(empty($group_work_info)){
                $this->error('该拼团不存在');
            }
            if($group_work_info['status'] == 0){
                $this->error('该拼团还未发起成功');
            }
            if($group_work_info['status'] == 2){
                $this->error('该拼团已成功');
            }
            if($group_work_info['userid'] == $user_info['id']){
                $this->error('您已经参与该拼团了');
            }
            $data = [
                'order_sn'=>getOrderSn(),
                'kecheng_id'=>$info['id'],
                'price'=>$info['price'],
                'userid'=>$user_info['id'],
                'type'=>1,
                'group_work_id'=>$group_work_info['id'],
            ];
            Db::startTrans();
            try {
                $res = Order::create($data);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->apiError($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->apiError($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->apiError($e->getMessage());
            }
            if($res){
                $out_trade_no = $data['order_sn'];
                $amount =$info['price'];
                $jsapi = new Response();
                $result = $jsapi->wx_pay($out_trade_no, $amount, $user_info['openid']);
                $result = json_decode($result,true);
                return $this->success($result,'请求成功');
            }else{
                $this->error('请刷新重试');
            }
        }else{
            return $this->error('数据为空');
        }
    }
}
